<?php
namespace App\Http\Controllers\Backstage;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\RoomInfoVail;
use App\Http\Controllers\Validator\RoomWordbookVail;
use App\Model\Backstage\RoomInfo;
use App\Model\Backstage\RoomWordbook;
use App\Model\Backstage\RoomWordbookInfo;
use App\Model\Backstage\User;
use App\Tool\Error;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Illuminate\Support\Facades\Auth;

/**
 * Class AreaController
 * @package App\Http\Controllers\Backstage
 * 省市区街道sql控制器
 * date:2018-4-29
 */
class AreaController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 省市区三级联动
     */
    public function listArea(Request $request){
        $code = $request->input('code');
        if(!isset($code) || $code == ''){
            $list = DB::table('area')->where(['parentId' => 0, 'level' => 1])->get();
            $two_level = DB::table('area')->where(['parentId' => $list[0]->code])->get();
            $three_level = DB::table('area')->where(['parentId' => $two_level[0]->code])->get();
            $two_level[0]->child_list = $three_level;
            $list[0]->child_list = $two_level;
        }else{
            if(!$request->input('level')){
                return $this->error(Error::PARAM_MISSING);
            }
            $level = $request->input('level');
            if($level == 2){  //查二级
                $list = DB::table('area')->where(['parentId' => $code])->get();
                $three_level = DB::table('area')->where(['parentId' => $list[0]->code])->get();
                $list[0]->child_list = $three_level;
            }else{  //默认查三级
                $list = DB::table('area')->where(['parentId' => $code])->get();
            }
        }
        return $this->success('ok',$list);
    }

    /**
     * @param $code
     * @return mixed
     * 根据code获取位置名称
     */
    public static function getAreaName($code){

        $res =  DB::table('area')->where(['code' => $code])->value('name');
        if(!$res){
            return '';
        }
        return $res;
    }


    /**
     * @return \Illuminate\Http\JsonResponse
     * 获取城市默认名称 和对应区
     */
    public function getCity(){
        $area_list = DB::table('area')->where(['parentId' => $this->city_code])->get();
        $data = [
            'area_list'         => $area_list,
            'city_name'         => $this->city,
        ];
        return $this->success('ok', $data);
    }







}